package com.lfg.leetcode.leetcode0;


import java.util.ArrayList;
import java.util.List;

public class No54spiralOrder {

    public static void main(String[] args) {
        int[][] array = new int[3][1];
        array[0] = new int[]{3};
        array[1] = new int[]{2};
        array[2] = new int[]{1};
//        array[1] = new int[]{5, 6, 7};
//        array[2] = new int[]{9, 10, 11};
//        array[3] = new int[]{13, 14, 15, 16};
        List<Integer> ret = spiralOrder(array);
        System.out.println(ret);
    }


    public static List<Integer> spiralOrder(int[][] matrix) {

        if (matrix.length == 0) {
            return new ArrayList<>();
        }
        List<Integer> ret = new ArrayList<>(matrix.length * matrix[0].length);
        int[] seq = new int[]{0, matrix[0].length - 1, matrix.length - 1, 0};
        int times = matrix.length / 2;
        if ((matrix.length & 1) == 1) {
            times++;
        }
        for (int n = 0; n < times; n++) {
            int[] tmp = matrix[seq[0]];
            for (int index = n; index < tmp.length - n && seq[2] >= seq[0]; index++) {
                ret.add(tmp[index]);
            }
            seq[0]++;
            for (int rowNo = n + 1; rowNo < matrix.length - n - 1 && seq[3] <= seq[1]; rowNo++) {
                ret.add(matrix[rowNo][seq[1]]);
            }
            seq[1]--;
            tmp = matrix[seq[2]];
            for (int index = tmp.length - n - 1; index >= n && seq[2] >= seq[0]; index--) {
                ret.add(tmp[index]);
            }
            seq[2]--;
            for (int rowNo = matrix.length - n - 2; rowNo > n && seq[3] <= seq[1]; rowNo--) {
                ret.add(matrix[rowNo][seq[3]]);
            }
            seq[3]++;
            if (seq[0] < 0 || seq[1] < 0 || seq[2] < 0 || seq[3] < 0) {
                break;
            }
        }
        return ret;
    }


}

